package com.printeverywhere.util;


import java.util.Calendar;

import org.apache.log4j.Logger;

import com.paypal.sdk.exceptions.PayPalException;
import com.paypal.sdk.profiles.APIProfile;
import com.paypal.sdk.profiles.ProfileFactory;
import com.paypal.sdk.services.CallerServices;
import com.paypal.soap.api.AddressType;
import com.paypal.soap.api.BasicAmountType;
import com.paypal.soap.api.CountryCodeType;
import com.paypal.soap.api.CreditCardDetailsType;
import com.paypal.soap.api.CreditCardTypeType;
import com.paypal.soap.api.CurrencyCodeType;
import com.paypal.soap.api.DoDirectPaymentRequestDetailsType;
import com.paypal.soap.api.DoDirectPaymentRequestType;
import com.paypal.soap.api.DoDirectPaymentResponseType;
import com.paypal.soap.api.GetTransactionDetailsRequestType;
import com.paypal.soap.api.GetTransactionDetailsResponseType;
import com.paypal.soap.api.PayerInfoType;
import com.paypal.soap.api.PaymentActionCodeType;
import com.paypal.soap.api.PaymentDetailsType;
import com.paypal.soap.api.PaymentTransactionSearchResultType;
import com.paypal.soap.api.PaymentTransactionType;
import com.paypal.soap.api.PersonNameType;
import com.paypal.soap.api.TransactionSearchRequestType;
import com.paypal.soap.api.TransactionSearchResponseType;
import com.printeverywhere.dto.Creditcard;

/**
 * PayPal Java SDK sample application
 */
public class PayPalUtil {
	private static Logger logger = Logger.getLogger(PayPalUtil.class);
	static CallerServices caller;

    public static void main(String[] args) {
    	try {


    		PayPalUtil app =	new PayPalUtil();
    		app.run();
		}
    	catch (Exception e) {
    		System.out.println("ERROR: " + e.getMessage());
		}
    }

    public PayPalUtil() throws PayPalException {
    	caller = new CallerServices();

    	/*
    	 WARNING: Do not embed plaintext credentials in your application code.
    	 Doing so is insecure and against best practices.
    	 Your API credentials must be handled securely. Please consider
    	 encrypting them for use in any production environment, and ensure
    	 that only authorized individuals may view or modify them.
    	 */

    	APIProfile profile = ProfileFactory.createSSLAPIProfile();
    	profile.setAPIUsername("sdk-seller_api1.sdk.com");
    	profile.setAPIPassword("12345678");
    	profile.setCertificateFile("Cert/sdk-seller.p12");
    	profile.setPrivateKeyPassword("password");
    	profile.setEnvironment("beta-sandbox");
    	caller.setAPIProfile(profile);
    }

    public void run() throws PayPalException {
    	TransactionSearch();
		/*GetTransactionDetails();
		DoDirectPayment();
		System.out.println("\nDone...");*/
    }



    public static void TransactionSearch() throws PayPalException {
    	System.out.println("\n########## Transaction Search ##########\n");
		TransactionSearchRequestType request = new TransactionSearchRequestType();
		Calendar calendar = Calendar.getInstance();
		calendar.set(2005,2,25);
		request.setStartDate(calendar);
		request.setTransactionID("1J110007888511720");

		TransactionSearchResponseType response = (TransactionSearchResponseType) caller.call("TransactionSearch", request);
		System.out.println("Operation Ack: " + response.getAck());
		System.out.println("---------- Results ----------");

		// Check to see if any transactions were found
		PaymentTransactionSearchResultType[] ts = response.getPaymentTransactions();
		if (ts != null)
		{
			System.out.println("Found " + ts.length + " records");

			// Display the results of the first transaction returned
			for (int i = 0; i < ts.length; i++)
			{
				System.out.println("\nTransaction ID: " + ts[i].getTransactionID());
				System.out.println("Payer Name: " + ts[i].getPayerDisplayName());
				System.out.println("Gross Amount: " + ts[i].getGrossAmount().getCurrencyID() + " " + ts[i].getGrossAmount().get_value());
				System.out.println("Fee Amount: " + ts[i].getFeeAmount().getCurrencyID() + " " + ts[i].getFeeAmount().get_value());
				System.out.println("Net Amount: " + ts[i].getNetAmount().getCurrencyID() + " " + ts[i].getNetAmount().get_value());
			}
		}
		else
		{
			System.out.println("Found 0 transaction");
		}
    }

    public static void GetTransactionDetails() throws PayPalException {
    	System.out.println("\n########## Get Transaction Details ##########\n");
		GetTransactionDetailsRequestType request = new GetTransactionDetailsRequestType();
 	  	request.setTransactionID("7J110007888511720");

 	  	GetTransactionDetailsResponseType response = (GetTransactionDetailsResponseType) caller.call("GetTransactionDetails", request);
 	  	System.out.println("Operation Ack: " + response.getAck());
 	  	System.out.println("---------- Results ----------");

 	  	PaymentTransactionType ts = response.getPaymentTransactionDetails();
 	  	System.out.println("\nTransaction ID: " + ts.getPaymentInfo().getTransactionID());
 	  	System.out.println("Payer Name: " + ts.getPayerInfo().getPayer());
 	  	System.out.println("Receiver Name: " + ts.getReceiverInfo().getReceiver());
 	  	System.out.println("Gross Amount: " + ts.getPaymentInfo().getGrossAmount().getCurrencyID() + " " + ts.getPaymentInfo().getGrossAmount().get_value());
    }

    public static DoDirectPaymentResponseType DoDirectPayment(CallerServices caller, Creditcard  creditcard, double amount, String currency) throws PayPalException {
    	DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
		DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();
		DoDirectPaymentResponseType response = null;
    	try{
			CreditCardDetailsType creditCard = new CreditCardDetailsType();
			creditCard.setCreditCardNumber("4721930402892796");
			creditCard.setCreditCardType(CreditCardTypeType.Visa);

			creditCard.setCVV2("000");
			creditCard.setExpMonth(new Integer(11));
			creditCard.setExpYear(new Integer(2010));

			PayerInfoType cardOwner = new PayerInfoType();
			cardOwner.setPayerCountry(CountryCodeType.US);

			AddressType address = new AddressType();
			address.setPostalCode("95101");
			address.setStateOrProvince("CA");
			address.setStreet1("123 Main St");
			address.setCountryName("US");
			address.setCountry(CountryCodeType.US);
			address.setCityName("San Jose");
			cardOwner.setAddress(address);

			PersonNameType payerName = new PersonNameType();
			payerName.setFirstName("SDK");
			payerName.setLastName("Buyer");
			cardOwner.setPayerName(payerName);

			creditCard.setCardOwner(cardOwner);
			details.setCreditCard(creditCard);

			details.setIPAddress("127.0.0.1");
			details.setMerchantSessionId("456977");
			details.setPaymentAction(PaymentActionCodeType.Sale);

			PaymentDetailsType payment = new PaymentDetailsType();

			BasicAmountType orderTotal = new BasicAmountType();
			orderTotal.setCurrencyID(CurrencyCodeType.fromString(currency));
			orderTotal.set_value(String.valueOf(amount));
			payment.setOrderTotal(orderTotal);

			details.setPaymentDetails(payment);
			request.setDoDirectPaymentRequestDetails(details);

			response = (DoDirectPaymentResponseType) caller.call("DoDirectPayment", request);

	    	System.out.println("Operation Ack: " + response.getAck());
	 	  	System.out.println("---------- Results ----------");
	 	  	System.out.println("\nTransaction ID: " + response.getTransactionID());
	 	  	System.out.println("CVV2: " + response.getCVV2Code());
	 	  	System.out.println("AVS: " + response.getAVSCode());
	 	  	System.out.println("Gross Amount: " + response.getAmount().getCurrencyID()
				+ " " + response.getAmount().get_value());
    	}catch (Exception e) {
    		logger.error(e.getMessage());
		}
 	  	return response;
    }
} // SampleApp